package com.zc.controller.oldStore;

import com.zc.dto.ResultDto;
import com.zc.entity.Nav;
import com.zc.entity.Users;
import com.zc.service.JedisClient;
import com.zc.service.permissionService.PermissionService;
import com.zc.vo.LoginInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
public class WebloginController extends BaseController {
    @Resource
    private PermissionService permissionBiz;

    @Resource
    private JedisClient jedis;

    @ResponseBody
    @RequestMapping("/login")
    public ResultDto login(HttpServletRequest request, LoginInfo login, Model model) {
        ResultDto result = new ResultDto();
        Subject subject = SecurityUtils.getSubject();
        String username = login.getUsername();
        String password = login.getPassword();
        String YZMCode = login.getYzmCode();
        String identification = login.getIdentification();
        LOG.debug(login.toString());
        //验证验证码的有效性
        if (!jedis.exists(identification)) {
            result.setResultData(false, 1, "验证码已经是失效,请重新输入", null);
            return result;
        } else if (!YZMCode.equalsIgnoreCase(jedis.get(identification))) {
            result.setResultData(false, 2, "验证码输入错误,请重新输入", null);
        }
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        Users userInfo = null;
        try {
            subject.login(token);
            userInfo = (Users) subject.getPrincipal();
            request.getSession().setAttribute(userInfo.getId() + "", userInfo);
            result.setResultData(true, 0, "登入成功", null);
        } catch (Exception e) {
            LOG.error("login error::,{}", e);
            result.setResultData(false, 999, "出错了,请联系管理员", null);
        }
        return result;
    }

}

